package com.lanou3g.code0418.dirty;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by dllo on 18/4/17.
 */
//多线程模型下都加锁
public class Utils {


    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    //两个线程同时写一个对象，不允许产生的数据产生了叫做脏数据   eg：c 2
    public void updatePerson(Person person, String name, int age) {

        lock.writeLock().lock(); //通过读写锁 获得一个写锁，然后锁上

        person.setName(name);
        try {
            //让线程沉睡1s，为了让脏读效果更容易出现
            Thread.sleep(1000);//1000 ms
        } catch (Exception e) {
            e.printStackTrace();
        }
        person.setAge(age);

        lock.writeLock().unlock();
    }


    public void showPerson(Person person) {
        //使用synchronized lock 效率低下，因为如果没有修改需求，只读 仍然需要等 排队等待
        System.out.println(Thread.currentThread().getName() + "dfsdfsdf");
        lock.readLock().lock();


        System.out.println(Thread.currentThread().getName());
        try {
            Thread.sleep(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("姓名:" + person.getName());
        System.out.println("年龄：" + person.getAge());
        lock.readLock().unlock();

    }


}
